<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org" >
<head>
    <th:block th:include="include :: header('Power Statistics')" />
    <th:block th:include="include :: bootstrap-select-css" />
    <th:block th:include="include :: datetimepicker-css" />
    <!-- 添加标签页样式 -->
    <style>
        .nav-tabs-custom {
            margin-bottom: 20px;
            background: #fff;
            box-shadow: 0 1px 1px rgba(0,0,0,0.1);
            border-radius: 3px;
        }
        .nav-tabs-custom > .nav-tabs {
            margin: 0;
            border-bottom-color: #f4f4f4;
        }
        .nav-tabs-custom > .nav-tabs > li {
            margin-right: 5px;
        }
        .nav-tabs-custom > .nav-tabs > li > a {
            color: #444;
            border-radius: 0;
        }
        .nav-tabs-custom > .nav-tabs > li.active > a {
            border-left-color: #f4f4f4;
            border-right-color: #f4f4f4;
        }
        .trend-chart {
            height: 300px;
            width: 100%;
        }
        .current-date {
            font-size: 16px;
            font-weight: bold;
            margin: 10px 0;
            text-align: center;
        }
    </style>
</head>
<body class="gray-bg">
    <div class="wrapper wrapper-content animated fadeInRight">
        <div class="row">
            <div class="col-sm-12">
                <div class="ibox float-e-margins">
                    <div class="ibox-title">
                        <h5 id="currentDateTitle"></h5>
                        <div class="ibox-tools">
                            <a class="collapse-link">
                                <i class="fa fa-chevron-up"></i>
                            </a>
                            <a class="dropdown-toggle" data-toggle="dropdown">
                                <i class="fa fa-wrench"></i>
                            </a>
                            <ul class="dropdown-menu dropdown-user">
                                <li><a href="javascript:void(0)" onclick="$.table.exportExcel()">导出数据</a></li>
                                <li><a th:href="@{/system/meterdata/detail}">查看数据明细</a></li>
                            </ul>
                            <a class="close-link">
                                <i class="fa fa-times"></i>
                            </a>
                        </div>
                    </div>
                    <div class="ibox-content">
                        <!-- 添加四个刻度圆盘 -->
                        <div class="row">
                            <div class="col-sm-3">
                                <div class="panel panel-success">
                                    <div class="panel-heading">
                                        日用电量
                                    </div>
                                    <div class="panel-body text-center">
                                        <div id="dayGaugeValue" class="h3 m-t-xs">0 kWh</div>
                                    </div>
                                </div>
                            </div>
                            <div class="col-sm-3">
                                <div class="panel panel-info">
                                    <div class="panel-heading">
                                        周用电量
                                    </div>
                                    <div class="panel-body text-center">
                                        <span id="weekGauge" class="sparkline-gauge"></span>
                                        <div id="weekGaugeValue" class="h3 m-t-xs">0 kWh</div>
                                    </div>
                                </div>
                            </div>
                            <div class="col-sm-3">
                                <div class="panel panel-warning">
                                    <div class="panel-heading">
                                        月用电量
                                    </div>
                                    <div class="panel-body text-center">
                                        <span id="monthGauge" class="sparkline-gauge"></span>
                                        <div id="monthGaugeValue" class="h3 m-t-xs">0 kWh</div>
                                    </div>
                                </div>
                            </div>
                            <div class="col-sm-3">
                                <div class="panel panel-danger">
                                    <div class="panel-heading">
                                        年用电量
                                    </div>
                                    <div class="panel-body text-center">
                                        <span id="yearGauge" class="sparkline-gauge"></span>
                                        <div id="yearGaugeValue" class="h3 m-t-xs">0 kWh</div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        <!-- 添加标签页 -->
                        <div class="row">
                            <div class="col-sm-12">
                                <div class="nav-tabs-custom">
                                    <ul class="nav nav-tabs">
                                        <li class="active"><a href="#hourTab" data-toggle="tab">小时统计</a></li>
                                        <li><a href="#dayTab" data-toggle="tab">日统计</a></li>
                                        <li><a href="#monthTab" data-toggle="tab">月统计</a></li>
                                        <li><a href="#yearTab" data-toggle="tab">年统计</a></li>
                                    </ul>
                                    <div class="tab-content">
                                        <div class="tab-pane active" id="hourTab">
                                            <div class="trend-chart" id="hourChart"></div>
                                        </div>
                                        <div class="tab-pane" id="dayTab">
                                            <div class="trend-chart" id="dayChart"></div>
                                        </div>
                                        <div class="tab-pane" id="monthTab">
                                            <div class="trend-chart" id="monthChart"></div>
                                        </div>
                                        <div class="tab-pane" id="yearTab">
                                            <div class="trend-chart" id="yearChart"></div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <th:block th:include="include :: footer" />
    <th:block th:include="include :: bootstrap-select-js" />
    <!-- 替换Sparkline为ECharts -->
    <th:block th:include="include :: echarts-js" />
    
    <script th:inline="javascript">
        var prefix = ctx + "system/meterdata";
        var sparklineData = [];
        var sparklineLabels = [];
        
        $(function() {
            // 显示当前日期作为标题
            updateCurrentDateTitle();
            
            // 初始化四个刻度圆盘
            initGauges();
            
            // 更新四个刻度圆盘数据
            updateGauges();
            
            // 每隔5分钟更新一次圆盘数据
            setInterval(updateGauges, 300000);
            
            // 加载各标签页数据
            loadHourData();
            loadDayData();
            loadMonthData();
            loadYearData();
            
            // 标签页切换事件
            $('a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
                var target = $(e.target).attr("href");
                if (target === "#hourTab") {
                    loadHourData();
                } else if (target === "#dayTab") {
                    loadDayData();
                } else if (target === "#monthTab") {
                    loadMonthData();
                } else if (target === "#yearTab") {
                    loadYearData();
                }
            });
        });
        
        // 更新当前日期显示为标题
        function updateCurrentDateTitle() {
            var today = getNowFormatDate();
            $('#currentDateTitle').text(today);
        }
        
        // 获取当前日期
        function getNowFormatDate() {
            var date = new Date();
            var year = date.getFullYear();
            var month = date.getMonth() + 1;
            var day = date.getDate();
            
            if (month < 10) month = "0" + month;
            if (day < 10) day = "0" + day;
            
            return year + "-" + month + "-" + day;
        }
        
        // 加载小时统计数据
        function loadHourData() {
            var today = getNowFormatDate();
            $.ajax({
                url: prefix + '/statisticsByHour',
                type: 'GET',
                data: {date: today},
                success: function(result) {
                    if (result.code === 0) {
                        // 直接使用后端返回的数据
                        var data = result.data;
                        
                        // 按小时排序数据
                        if (data && data.length > 0) {
                            data.sort(function(a, b) {
                                return parseInt(a.hour) - parseInt(b.hour);
                            });
                        }
                        
                        renderChart('#hourChart', data, 'hour', '小时用电量趋势');
                    } else {
                        $.modal.alertError("查询失败：" + result.msg);
                    }
                },
                error: function() {
                    $.modal.alertError("查询失败，请检查网络连接");
                }
            });
        }
        
        // 加载日统计数据
        function loadDayData() {
            var date = new Date();
            var firstDay = new Date(date.getFullYear(), date.getMonth(), 1);
            var lastDay = new Date(date.getFullYear(), date.getMonth() + 1, 0);
            
            var startDate = formatDate(firstDay);
            var endDate = formatDate(lastDay);
            
            $.ajax({
                url: prefix + '/statisticsByDay',
                type: 'POST',  // 这里使用POST方法是正确的
                data: {startDate: startDate, endDate: endDate},
                success: function(result) {
                    if (result.code === 0) {
                        renderChart('#dayChart', result.data, 'date', '日用电量趋势');
                    } else {
                        $.modal.alertError("查询失败：" + result.msg);
                    }
                },
                error: function(xhr, status, error) {
                    console.error("AJAX错误:", status, error);
                    console.log("响应文本:", xhr.responseText);
                    $.modal.alertError("查询失败，请检查网络连接和服务器日志");
                }
            });
        }
        
        // 加载月统计数据
        function loadMonthData() {
            var date = new Date();
            var year = date.getFullYear();
            var month = date.getMonth() + 1;
            if (month < 10) month = "0" + month;
            var yearMonth = year + "-" + month;
            
            $.ajax({
                url: prefix + '/statisticsByMonth',
                type: 'POST',
                data: {yearMonth: yearMonth},
                success: function(result) {
                    if (result.code === 0) {
                        renderChart('#monthChart', result.data, 'month', '月用电量趋势');
                    } else {
                        $.modal.alertError("查询失败：" + result.msg);
                    }
                },
                error: function() {
                    $.modal.alertError("查询失败，请检查网络连接");
                }
            });
        }
        
        // 加载年统计数据
        function loadYearData() {
            var currentYear = new Date().getFullYear();
            var startYear = currentYear - 5;
            var endYear = currentYear;
            
            $.ajax({
                url: prefix + '/statisticsByYear',
                type: 'POST',
                data: {startYear: startYear, endYear: endYear},
                success: function(result) {
                    if (result.code === 0) {
                        renderChart('#yearChart', result.data, 'year', '年用电量趋势');
                    } else {
                        $.modal.alertError("查询失败：" + result.msg);
                    }
                },
                error: function() {
                    $.modal.alertError("查询失败，请检查网络连接");
                }
            });
        }
        
        // 渲染图表
        // 渲染图表
        function renderChart(container, data, labelField, title) {
            var chartData = [];
            var chartLabels = [];
            var myChartInstance = null; // 保存图表实例的引用
            
            console.log("渲染图表", container, data);
            
            if (data && data.length > 0) {
                for (var i = 0; i < data.length; i++) {
                    var item = data[i];
                    chartData.push(item.energy ? parseFloat(item.energy) : 0);
                    chartLabels.push(item[labelField]);
                }
                
                // 清空容器
                $(container).empty();
                
                // 确保容器可见并有高度
                $(container).css({
                    'height': '300px',
                    'width': '100%',
                    'visibility': 'visible',
                    'display': 'block' // 确保容器显示
                });
                
                console.log("容器尺寸：", $(container).width(), $(container).height());
                
                // 立即初始化ECharts实例
                try {
                    console.log("初始化ECharts实例", container);
                    
                    // 确保DOM元素存在
                    var domElement = $(container)[0];
                    if (!domElement) {
                        console.error("找不到DOM元素", container);
                        return;
                    }
                    
                    // 如果已存在实例，先销毁
                    var existingChart = echarts.getInstanceByDom(domElement);
                    if (existingChart) {
                        existingChart.dispose();
                    }
                    
                    myChartInstance = echarts.init(domElement);
                    
                    // 指定图表的配置项和数据
                    var option = {
                        title: {
                            text: title,
                            left: 'center'
                        },
                        tooltip: {
                            trigger: 'axis',
                            formatter: function(params) {
                                return params[0].name + ': ' + params[0].value + ' kWh';
                            }
                        },
                        grid: {
                            left: '3%',
                            right: '4%',
                            bottom: '3%',
                            containLabel: true
                        },
                        xAxis: {
                            type: 'category',
                            data: chartLabels,
                            name: '时间',
                            nameLocation: 'middle',
                            nameGap: 30,
                            axisLabel: {
                                interval: function(index, value) {
                                    // 根据数据量调整显示的标签数量
                                    var maxLabels = Math.min(24, chartLabels.length);
                                    var step = Math.max(1, Math.floor(chartLabels.length / maxLabels));
                                    return index % step === 0;
                                },
                                rotate: chartLabels.length > 12 ? 45 : 0
                            }
                        },
                        yAxis: {
                            type: 'value',
                            name: '用电量(kWh)',
                            nameLocation: 'middle',
                            nameGap: 50,
                            axisLine: {
                                show: true
                            },
                            axisTick: {
                                show: true
                            },
                            splitLine: {
                                show: true
                            }
                        },
                        series: [{
                            name: '用电量',
                            type: 'line',  // 面积图类型
                            data: chartData,
                            areaStyle: {}, // 添加面积样式
                            itemStyle: {
                                color: '#1ab394'
                            },
                            lineStyle: {
                                width: 2
                            },
                            smooth: true // 平滑曲线
                        }]
                    };
                    
                    // 使用刚指定的配置项和数据显示图表
                    myChartInstance.setOption(option);
                    console.log("图表渲染完成", container);
                    
                    // 保存图表实例到DOM元素
                    $(domElement).data('echarts-instance', myChartInstance);
                    
                    // 强制执行一次重绘
                    setTimeout(function() {
                        if (myChartInstance && !myChartInstance.isDisposed()) {
                            myChartInstance.resize();
                        }
                    }, 200);
                    
                    // 响应窗口大小变化，重绘图表
                    var resizeHandler = function() {
                        var chart = $(domElement).data('echarts-instance');
                        if (chart && !chart.isDisposed()) {
                            chart.resize();
                        }
                    };
                    
                    // 移除之前的resize事件处理器
                    $(window).off('resize.echarts' + container.replace('#', ''));
                    
                    // 添加新的resize事件处理器
                    $(window).on('resize.echarts' + container.replace('#', ''), resizeHandler);
                    
                    // 标签页切换时重新调整大小
                    $('a[data-toggle="tab"]').off('shown.bs.tab.echarts' + container.replace('#', ''));
                    $('a[data-toggle="tab"]').on('shown.bs.tab.echarts' + container.replace('#', ''), function (e) {
                        var target = $(e.target).attr("href");
                        var targetContainer = null;
                        
                        if (target === "#hourTab") targetContainer = "#hourChart";
                        else if (target === "#dayTab") targetContainer = "#dayChart";
                        else if (target === "#monthTab") targetContainer = "#monthChart";
                        else if (target === "#yearTab") targetContainer = "#yearChart";
                        
                        if (targetContainer === container) {
                            console.log("标签页切换到", target, "重新调整图表大小", container);
                            setTimeout(function() {
                                var chart = $(domElement).data('echarts-instance');
                                if (chart && !chart.isDisposed()) {
                                    chart.resize();
                                }
                            }, 100);
                        }
                    });
                } catch (e) {
                    console.error("ECharts初始化错误:", e);
                    $(container).html('<div class="empty-data" style="text-align: center; padding: 50px 0;">图表初始化失败: ' + e.message + '</div>');
                }
            } else {
                $(container).html('<div class="empty-data" style="text-align: center; padding: 50px 0;">暂无数据</div>');
            }
        }
        
        // 格式化日期
        function formatDate(date) {
            var year = date.getFullYear();
            var month = date.getMonth() + 1;
            var day = date.getDate();
            
            if (month < 10) month = "0" + month;
            if (day < 10) day = "0" + day;
            
            return year + "-" + month + "-" + day;
        }
        
        // 修改 initGauges 函数
        function initGauges() {
            // 不再需要初始化仪表盘，只设置初始值
            $('#dayGaugeValue').text('0 kWh');
            $('#weekGaugeValue').text('0 kWh');
            $('#monthGaugeValue').text('0 kWh');
            $('#yearGaugeValue').text('0 kWh');
        }
        
        // 修改 updateGauges 函数中的相关部分
        function updateGauges() {
            // 获取各时间段的统计数据
            $.ajax({
                url: prefix + '/getLatestStatistics',
                type: 'POST',
                success: function(result) {
                    if (result.code === 0) {
                        var data = result.data;
                        
                        // 更新日用电量值
                        var dayValue = data.day ? parseFloat(data.day) : 0;
                        $('#dayGaugeValue').text(dayValue.toFixed(2) + ' kWh');
                        
                        // 更新周用电量值
                        var weekValue = data.week ? parseFloat(data.week) : 0;
                        $('#weekGaugeValue').text(weekValue.toFixed(2) + ' kWh');
                        
                        // 更新月用电量值
                        var monthValue = data.month ? parseFloat(data.month) : 0;
                        $('#monthGaugeValue').text(monthValue.toFixed(2) + ' kWh');
                        
                        // 更新年用电量值
                        var yearValue = data.year ? parseFloat(data.year) : 0;
                        $('#yearGaugeValue').text(yearValue.toFixed(2) + ' kWh');
                    }
                }
            });
        }
    </script>
</body>
</html>